package com.foxzzz.excelimport.util;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.event.AnalysisEventListener;
import com.alibaba.excel.support.ExcelTypeEnum;

import java.io.FileInputStream;
import java.io.InputStream;

public class ExcelUtil<T extends BaseRowModel> {
    private static final String XLSX = "XLSX";
    private ExcelReader excelReader;
    private ExcelLineHandler lineHandler;

    public ExcelUtil<T> prepare(String path) throws Exception {
        ExcelTypeEnum type = XLSX.equals(path.replaceAll(".*\\.", "")
                .toUpperCase()) ? ExcelTypeEnum.XLSX : ExcelTypeEnum.XLS;
        InputStream in = new FileInputStream(path);

        ExcelReader excelReader = new ExcelReader(in, type, null, new AnalysisEventListener<T>() {
            public void invoke(T t, AnalysisContext analysisContext) {
                lineHandler.handleLine(t);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            }
        });
        this.excelReader = excelReader;
        return this;
    }

    public ExcelReader getExcelReader() {
        return excelReader;
    }

    public void readExcel(Class<? extends BaseRowModel> model, int sheet, int headLineNum, ExcelLineHandler handler) throws Exception {
        this.lineHandler = handler;
        excelReader.read(new Sheet(sheet, headLineNum, model));
    }

    public static void main(String[] args) throws Exception {
        new ExcelUtil<Obj>().prepare("C:\\Users\\Dear_\\Desktop\\qiche01.xlsx")
                .readExcel(Obj.class,1,1, o -> {
                    System.out.println(o);
                });
    }
}
